<!-- 卖家 售后详情 -->
<template>
  <PublicPage pageName="售后详情" :borderType="true" :showNav="true">
    <view class="myAftersaleDetails">
      <!-- 头部+步骤条 start-->
      <view class="bgf u-m-b-20 flex-col justify-center items-center" style="height: 200rpx;">
        <view class="fz-24 tc" :class="{'themeFontColor': isThemeColor}">{{ orderAfterSalesItem.status }}</view>
      </view>
      
      <!-- 头部+步骤条 end-->
      <view class="bgf" style="height: calc(100% - 320rpx);">
        <view class="px32" style="border-bottom:solid 20rpx #F7F8FA;" v-if="orderAfterSalesItem.helpSellAccountId || orderAfterSalesItem.groupAccountId">
          <view class="linh-48 fz-16 fw5">订单关系</view>
          <view class="linh-48 justify-between items-center" v-if="orderAfterSalesItem.groupAccountId">
            <view class="u-flex">
              <text class="leftBox">供货</text>
              <image :src="orderAfterSalesItem.groupCommunityLogo" mode="aspectFill" style="width:64rpx;height:64rpx;border-radius: 50%;" />
              <view class="u-p-l-16 ov1" style="max-width:400rpx;">{{orderAfterSalesItem.groupCommunityName}}</view>
            </view>
            <view class="lianxiBtn" @click="connection(orderAfterSalesItem.groupAccountId)">
              联系TA
            </view>
          </view>
          <view class="linh-48 justify-between items-center" v-if="orderAfterSalesItem.helpSellAccountId">
            <view class="u-flex">
              <text class="leftBox">帮卖</text>
              <image :src="orderAfterSalesItem.helpSellCommunityLogo" mode="aspectFill" style="width:64rpx;height:64rpx;border-radius: 50%;" />
              <view class="u-p-l-16 ov1" style="max-width:400rpx;">{{orderAfterSalesItem.helpSellCommunityName}}</view>
            </view>
            <view class="lianxiBtn" @click="connection(orderAfterSalesItem.helpSellAccountId)">
              联系TA
            </view>
          </view>
        </view>
        <view class="justify-between px32 linh-48" style="box-shadow: inset 0px -1px 0px #EEEEEE;">
          <view>售后进度明细</view> 
          <view class="viceColor">{{orderAfterSalesItem.applyType === 1 ? '仅退款' : '退货退款 '}}</view>
        </view>
        <!-- 日志 -->
        <scroll-view scroll-y :style="jianquHeight">
          <AfterSalesProgress :afterSales="orderAfterSalesItem" />
        </scroll-view>
      </view>
  
      <!-- 底部固定按钮 -->
      <view class="bottomBtn">
        <button class="btn" @click="_copyAfterSale(orderAfterSalesId)">复制售后单</button>
        <button class="btn" v-if="orderAfterSalesItem.status === '待你处理' || orderAfterSalesItem.status === '买家已退货'" @click="refuseShow = true">拒绝申请</button>
        <button class="btn redBtn" v-if="orderAfterSalesItem.status === '待你处理'" @click="_agreeFn">同意申请</button>
        <button class="btn redBtn" v-if="orderAfterSalesItem.status === '买家已退货'" @click="agreeShow3 = true">确认退款</button>
      </view>




      <!-- 拒绝申请 -->
      <u-modal v-model="refuseShow" show-cancel-button confirm-text="拒绝申请" confirm-color="#E44435" cancel-text="稍后处理" title="拒绝售后申请" :title-style="{lineHeight: '44rpx',paddingBottom: '16rpx'}" @confirm="_configRefuse">
        <view>
          <view class="tc fz-12" style="color:#969799;">请说明拒绝理由</view>
          <view class="u-padding-30 u-padding-left-45 u-padding-right-45 placeholderClass">
            <u-input v-model="refuseText" type="textarea" :clearable="false" placeholder="请输入拒绝理由" :custom-style="{backgroundColor: '#F7F8FA',borderRadius: '16rpx',minHeight: '240rpx',padding: '24rpx 32rpx'}" />
          </view>
        </view>
      </u-modal>
      <!-- 仅退款-同意申请 -->
      <u-modal v-model="agreeShow1 " show-cancel-button confirm-text="确定退款" confirm-color="#E44435" cancel-text="稍后处理" title="是否同意退款" :title-style="{lineHeight: '44rpx',paddingBottom: '16rpx'}" @confirm="_refundStep">
        <view slot="default">
          <view class="tc u-p-l-50 u-p-r-50 u-p-b-40 fz-14" style="color:#969799;">同意退款后，将直接从您的账户余额扣除退款金额给买家</view>
        </view>
      </u-modal> 
      <!-- 退货退款 -同意申请 -->
      <u-modal v-model="agreeShow2 " show-cancel-button confirm-text="确定" :confirm-color="returnAddress.id?'#E44435':'#FFE5DE'" cancel-text="稍后处理" title="同意退货退款" :title-style="{lineHeight: '44rpx',paddingBottom: '16rpx'}" 
      @confirm="_purchaseStep">
        <view slot="default">
          <view class="tc u-p-b-40 fz-14" style="color:#969799;">请选择商品退回的收货地址</view>
          <view class="justify-between items-center viceColor fz-14 u-m-l-32 u-m-r-32 u-m-b-50 u-p-l-20 u-p-r-20" style="background: #F7F8FA;height:160rpx;" @click="_goReturnAddress">
            <view></view>
            <view v-if="returnAddress.id" style="width:420rpx;color:#333;">
              <view class="ov1"><text>{{returnAddress.name}}</text><text class="u-p-l-20">{{returnAddress.mobile}}</text></view>
              <view class="ov1 u-p-t-10">{{returnAddress.provinceName}}{{returnAddress.cityName}}{{returnAddress.countyName}}{{returnAddress.addr}}</view>
            </view>
            <view v-else>请添加收货地址</view>
            <view><u-icon name="arrow-right" size="28"></u-icon></view>
          </view>
        </view>
      </u-modal>
      <!-- 退货退款 -确认退款 -->
      <u-modal v-model="agreeShow3 " show-cancel-button confirm-text="确认退款" confirm-color="#E44435" cancel-text="稍后处理" title="商品无误，确认退款" :title-style="{lineHeight: '44rpx',paddingBottom: '16rpx'}" 
      @confirm="_refundStep">
        <view slot="default">
          <view class="tc u-p-l-50 u-p-r-50 u-p-b-40 fz-14" style="color:#969799;">同意退款后，将直接从您的账户余额扣除退款金额给买家</view>
        </view>
      </u-modal>
      <!-- 退款失败 --> 
      <u-modal v-model="errorShow " show-cancel-button confirm-text="前往充值" confirm-color="#E44435" cancel-text="稍后处理" title="退款失败!" :title-style="{color: '#E44435',lineHeight: '44rpx',paddingBottom: '16rpx'}" 
      @confirm="_goRecharge">
        <view slot="default">
          <view class="tc u-p-l-50 u-p-r-50 u-p-b-40 fz-14" style="color:#969799;">账户余额不足以支付退款金额，当前订单需退款{{orderAfterSalesItem.orderAfterSalesInformationVO.totalApplyAmount || ''}}元，还差{{rechargeAmount}}元，请充值</view>
        </view>
      </u-modal>
      <!-- 退款成功 --> 
      <!-- <u-modal v-model="successShow " confirm-text="确定" confirm-color="#E44435" title="退款处理成功!" :title-style="{lineHeight: '44rpx',paddingBottom: '16rpx'}" 
      @confirm="successShow = false">
        <view slot="default">
          <view class="tc u-p-l-50 u-p-r-50 u-p-b-40 fz-14" style="color:#969799;">退款处理已移交微信支付处理，受理成功后将原路退回至团员支付账户</view>
        </view>
      </u-modal> -->
    </view>
  </PublicPage>
</template>
<script>
import PublicPage from "@/components/publicPage/index.vue";
import AfterSalesProgress from "./afterSalesProgress.vue";
import orderApi from "@/api/orderApi.js";
import user from "@/api/user.js";
import { comparedValue, aftersaleReason } from "@/utils/statusList"


export default {
  components: {
    PublicPage,
    AfterSalesProgress
  },
  computed: {
    // 标题是否红色
    isThemeColor(){
      return this.orderAfterSalesItem.status === '已拒绝申请'
    },
    // 退货地址
    returnAddress(){
      return this.$store.state.choiceAddressData || {}
    }
  },
  onLoad(options){
    this.orderAfterSalesId = options.orderAfterSalesId
    this._getSellerGetAfterDetails()
  },
  data() {
    return {
      orderAfterSalesId: '', // 售后ID
      orderAfterSalesItem: {}, // 售后对象
      refuseShow: false, // 拒绝申请售后弹窗
      refuseText: "", // 拒绝理由
      agreeShow1: false, // 仅退款-同意申请
      agreeShow2: false, // 退货退款-同意申请
      userAddress: {}, // 收货地址
      agreeShow3: false, // 退货退款-确认退款
      errorShow: false, // 退款失败
      // successShow: false, // 退款成功
      rechargeAmount: 0, // 充值金额
      jianquHeight: "height: calc(100% - 96rpx);",
    }
  },
  methods:{
    // 卖家获取售后详情
    _getSellerGetAfterDetails(){
      orderApi.sellerGetAfterDetails({orderAfterSalesId: this.orderAfterSalesId}).then(res=>{
        this.orderAfterSalesItem = res.data
        if(res.data.groupAccountId && res.data.helpSellAccountId){ // 都存在
          this.jianquHeight = "height: calc(100% - 384rpx);"
        }else if(res.data.groupAccountId || res.data.helpSellAccountId){
          this.jianquHeight = "height: calc(100% - 288rpx);"
        }else{
          this.jianquHeight = "height: calc(100% - 96rpx);"
        }
      })
    },
    // 拒绝售后
    _configRefuse(){
      if(!this.refuseText){
        uni.showToast({
          title: '请填写拒绝原因',
          icon: 'none'
        })
        return
      }
      let params = {
         orderAfterSalesId: this.orderAfterSalesId,
         rejectedReason: this.refuseText,
         runExamineStatus: 2 // 审核状态（1.通过申请 2.驳回 
      }
      orderApi.auditOrderAfterSales(params).then(res=>{
        if(res.code === 200){
          this._getSellerGetAfterDetails() // 刷新售后详情
        }else{
          uni.showToast({
            title: res.desc || '操作失败，请重试',
            icon: 'none'
          })
        }
      })
    },
    // 同意申请售后，判断是仅退款还是退货退款，有退货需要填写收货地址 
    async _agreeFn(){
      if(this.orderAfterSalesItem.applyType === 1 ){
        this.agreeShow1 = true
      }else{
        if(this.orderAfterSalesItem.isAddress === 1){ // 供货同意
          const { data } = await user.getSellerDefault() // 获取退货默认地址
          data && this.$store.commit("CHOICE_ADDRESS_DATA",data)
          this.agreeShow2 = true
        }else{ // 帮卖同意 -不用填地址
          let params = {
            orderAfterSalesId: this.orderAfterSalesId,
            runExamineStatus: 1 // 审核状态（1.通过申请 2.驳回 
          }
          orderApi.auditOrderAfterSales(params).then(res=>{
            if(res.code === 200){
              this._getSellerGetAfterDetails() // 刷新售后详情
            }else{
              uni.showToast({
                title: res.desc || '操作失败，请重试',
                icon: 'none'
              })
            }
          })
        }
      }
    },
    // 退款>同意
    _refundStep(){
      let params = {
         orderAfterSalesId: this.orderAfterSalesId,
         runExamineStatus: 1 // 审核状态（1.通过申请 2.驳回 
      }
      orderApi.auditOrderAfterSales(params).then(res=>{
        this.agreeShow1 = false
        this.agreeShow3 = false
        if(res.code === 200){
          // this.successShow = true // 退款成功
          this._getSellerGetAfterDetails() // 刷新售后详情
        }else if(res.code === 2002){
          this.rechargeAmount = res.data <= 0.1 ? 0.1 : res.data // 需充值金额
          this.errorShow = true //余额不足，退款失败
        }else{
          uni.showToast({
            title: res.desc || '操作失败，请重试',
            icon: 'none'
          })
        }
      })
    },
    // 退货退款>填写收货地址
    _purchaseStep(){
      this.agreeShow2 = true
      if(!this.returnAddress.id) return // 未填写收货地址
      let params = {
        orderAfterSalesId: this.orderAfterSalesId,
        userAddressId: this.returnAddress.id   
      }
      orderApi.addSellerAdders(params).then(res=>{
        this.agreeShow2 = false     
        this._getSellerGetAfterDetails() // 刷新售后详情
      })
    },
    // 选择退货地址
    _goReturnAddress(){
      uni.navigateTo({url: '/pagesB/addressLibrary/index?type=2&userType=seller'});
    },
    // 跳转去充值页面
    _goRecharge(){
      const that = this
      orderApi.tradeRecharge({rechargeMoney: that.rechargeAmount}).then(res=>{
        let payRes = res.data.weChatRespVO
        wx.requestPayment({
          timeStamp: payRes.timeStamp,
          nonceStr: payRes.nonceStr,
          package: payRes.packageInfo,
          signType: payRes.signType,
          paySign: payRes.paySign,
          success (res_) {
            if (res_.errMsg == 'requestPayment:ok') {
              that.errorShow = false
              that._refundStep() // 充值成功，重新退款
            }
          },
          fail (res_) {
            console.log(res_,'取消')
          }
        })
      })
    },
    // 联系团长
    connection(groupAccountId){
      if(this.$store.state.imUserInfo.imId === groupAccountId){
        uni.showToast({
          title: '不能联系自己',
          icon: 'none'
        });
        return
      }else{
        this.navigateTo({url: '/pagesB/message/messageDetails?id='+groupAccountId})
      }
    },
    // 复制售后单
    async _copyAfterSale(orderAfterSalesId){
      const { data } = await orderApi.copyAfterSale({orderAfterSalesId})
      let params = ``
      params += `跟团号：${data.followGroupNum}\n`
      params += `订单编号：${data.orderAllId}\n`
      params += `团员微信昵称：${data.nickname}\n`
      params += `申请退款金额：${data.totalApplyAmount}\n`
      params += `申请退款商品明细：${data.orderGoodsDetailVO.goodsName}（￥${data.orderGoodsDetailVO.totalApplyAmount}）\n`
      params += `团员退款原因：${comparedValue(aftersaleReason,data.applyReason)}\n`
      params += `发货快递信息：`
      data.orderExpressInformationVOList.forEach(v => {
        params += `${v.logisticsName}：${v.logisticsCode} \n`
      });
      params += `买家收货地址：${data.receivingInformationVO.receiveName}  ${data.receivingInformationVO.receiveMobile}  ${data.receivingInformationVO.receiveAddress} \n`
      params += `退货快递信息：`
      data.orderAfterSalesExpressInformationVOList.forEach(v => {
        params += `${v.logisticsName}：${v.logisticsCode} \n`
      });
      uni.setClipboardData({
        data: params,
        showToast: false,
        success: function () {
          uni.showToast({
            title: '售后单已复制',
            icon: 'success'
          });
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.myAftersaleDetails{
  height: 100%;
  .ov1{
    @include toe();
  }
  .bgf{
    background-color: #FFF;
  }
  .lianxiBtn{
    height: 48rpx;
    line-height: 44rpx;
    border: solid 1px #DCDEE0;
    border-radius: 32rpx;
    padding: 0 16rpx;
    font-size: 24rpx;
  }
  .leftBox{
    color: #E44435;
    border: solid 1px #E44435;
    border-radius: 6rpx;
    padding: 0 6rpx;
    font-size: 24rpx;
    height: 40rpx;
    line-height: 34rpx;
    margin-right: 20rpx;
  }
  .bottomBtn{
    background-color: #FFF;
    position: fixed;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
    bottom: 0;
    left: 0;
    width: 100%;
    padding-left: 32rpx;
    padding-right: 32rpx;
    padding-top: 0;
    padding-bottom: 20rpx;
    padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    .btn{
      line-height: 60rpx;
      height: 60rpx;
      padding: 0 24rpx;
      border: 1px solid #DCDEE0;
      border-radius: 60rpx;
      font-size: 24rpx;
      margin-top: 20rpx;
    }
    .btn.redBtn{
      border: 1px solid #E44435;
      background-color: #E44435;
      color: #FFFFFF;
    }
    .btn+.btn{
      margin-left: 20rpx;
    }
  }
}
</style>
